package com.ruoyi.student.adopt;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.student.domain.StudentInfo;
import com.ruoyi.student.service.IStudentInfoService;
import com.ruoyi.system.service.ISysUserService;
import org.openoa.base.entity.BpmBusinessProcess;
import org.openoa.base.exception.AFBizException;
import org.openoa.base.interf.BpmBusinessProcessService;
import org.openoa.base.vo.BusinessDataVo;
import org.openoa.engine.lowflow.service.LFFormOperationAdaptor;
import org.openoa.engine.lowflow.vo.UDLFApplyVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 学籍异动流程适配类
 * 处理XJYDXG流程的审批逻辑，在流程完成且审批通过时修改学生状态
 * 学生ID使用当前登录用户的user_name（学号）
 */
@Service("XJYDXG") // Service名称与formCode一致，确保切面匹配
public class StudentStatusLFFormAdaptor implements LFFormOperationAdaptor<UDLFApplyVo> {

    private static final Logger log = LoggerFactory.getLogger(StudentStatusLFFormAdaptor.class);
    private static final String TARGET_FORM_CODE = "XJYDXG"; // 目标流程编码
    private static final Integer APPROVED_STATE = 2; // 流程已通过状态

    @Autowired
    private IStudentInfoService studentInfoService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private BpmBusinessProcessService bpmBusinessProcessService;

    /**
     * 流程完成时处理（核心逻辑：流程结束且通过后更新学生信息）
     */
    @Override
    public void finishData(BusinessDataVo businessDataVo) {
        if (!TARGET_FORM_CODE.equals(businessDataVo.getFormCode())) {
            log.debug("非目标流程，跳过处理，formCode:{}", businessDataVo.getFormCode());
            return;
        }
        log.info("开始处理学籍异动流程完成逻辑，businessDataVo:{}", businessDataVo);

        try {
            // 获取流程编号并查询流程状态
            String processNumber = businessDataVo.getProcessNumber();
            if (processNumber == null) {
                log.error("流程编号processNumber为空，无法查询流程状态");
                return;
            }
            BpmBusinessProcess process = bpmBusinessProcessService.getBpmBusinessProcess(processNumber);
            if (process == null) {
                log.error("未查询到流程信息，processNumber:{}", processNumber);
                return;
            }
            Integer processState = process.getProcessState();
            log.info("流程状态查询结果，processNumber:{}，state:{}", processNumber, processState);

            // 仅处理审批通过的流程
            if (processState == null || !APPROVED_STATE.equals(processState)) {
                log.info("流程未通过或状态异常，不执行更新，processNumber:{}，state:{}", processNumber, processState);
                return;
            }

            // 获取当前登录用户的user_name（学号）作为学生ID
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null || loginUser.getUsername() == null) {
                log.error("未获取到登录用户信息，无法获取学生ID");
                return;
            }
            String studentId = loginUser.getUsername(); // 学生ID=登录用户的user_name（学号）
            log.info("当前登录用户学号（学生ID）:{}", studentId);

            // 获取表单中的目标状态
            Map<String, Object> formFields = businessDataVo.getLfConditions();
            if (formFields == null) {
                formFields = businessDataVo.getObjectMap();
            }
            if (formFields == null || formFields.isEmpty()) {
                log.error("表单数据为空，无法获取目标状态");
                return;
            }
            log.info("表单数据：{}", formFields);

            Object targetStatusObj = formFields.get("targetStatus");
            if (targetStatusObj == null) {
                log.error("表单中未找到目标状态字段（targetStatus）");
                return;
            }
            String targetStatus = targetStatusObj.toString();
            log.info("提取到目标状态:{}", targetStatus);

            // 更新学生信息
            StudentInfo studentInfo = studentInfoService.selectStudentInfoByStudentId(studentId);
            if (studentInfo == null) {
                log.error("未找到学生信息，studentId:{}", studentId);
                return;
            }
            studentInfo.setStudentStatus(targetStatus);
            int rows = studentInfoService.updateStudentInfo(studentInfo);

            if (rows > 0) {
                log.info("学生状态更新成功，学号:{}，新状态:{}，processNumber:{}", studentId, targetStatus, processNumber);
            } else {
                log.warn("学生状态更新失败，学号:{}", studentId);
            }

        } catch (Exception e) {
            log.error("流程完成后更新学生信息异常", e);
        }
    }

    private boolean isTargetForm(UDLFApplyVo vo) {
        return TARGET_FORM_CODE.equals(vo.getFormCode());
    }

    @Override
    public void previewSetCondition(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        log.debug("执行previewSetCondition，vo:{}", vo);
    }

    @Override
    public void initData(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        log.debug("执行initData，vo:{}", vo);
        // 初始化时自动填充当前登录学生的信息
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null && loginUser.getUsername() != null) {
                String studentId = loginUser.getUsername();
                StudentInfo student = studentInfoService.selectStudentInfoByStudentId(studentId);
                if (student != null) {
                    // 向表单字段中填充学生信息（如姓名、当前状态）
                    Map<String, Object> lfFields = vo.getLfFields();
                    if (lfFields == null) {
                        lfFields = new HashMap<>();
                        vo.setLfFields(lfFields);
                    }
                    lfFields.put("studentId", "107622025201370"); // 显示学号（不可编辑）
                    lfFields.put("studentName", student.getStudentName());
                    lfFields.put("currentStatus", student.getStudentStatus());
                }
            }
        } catch (Exception e) {
            log.error("初始化表单数据异常", e);
        }
    }

    @Override
    public void launchParameters(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        log.debug("执行launchParameters，vo:{}", vo);
        previewSetCondition(vo);
    }

    @Override
    public void queryData(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        log.debug("执行queryData，vo:{}", vo);
        // 查询并回显当前登录学生的信息
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null || loginUser.getUsername() == null) {
                log.warn("queryData:未获取到登录用户信息");
                return;
            }
            String studentId = loginUser.getUsername(); // 学生ID=登录用户的user_name（学号）

            StudentInfo student = studentInfoService.selectStudentInfoByStudentId(studentId);
            if (student != null) {
                Map<String, Object> lfFields = vo.getLfFields();
                if (lfFields == null) {
                    lfFields = new HashMap<>();
                    vo.setLfFields(lfFields);
                }
                lfFields.put("studentName", student.getStudentName());
                lfFields.put("currentStatus", student.getStudentStatus());
                log.debug("回显学生信息，学号:{}，姓名:{}", studentId, student.getStudentName());
            } else {
                log.warn("queryData:未找到学生信息，学号:{}", studentId);
            }
        } catch (Exception e) {
            log.error("queryData:查询学生信息失败", e);
        }
    }

    @Override
    public void submitData(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        log.debug("执行submitData，vo:{}", vo);
        // 表单提交校验（无需校验学生ID，因为来自登录用户）
        Map<String, Object> formFields = vo.getLfFields();
        if (formFields == null) {
            throw new RuntimeException("表单数据为空");
        }
        Object targetStatusObj = formFields.get("targetStatus");
        if (targetStatusObj == null || targetStatusObj.toString().trim().isEmpty()) {
            throw new RuntimeException("请选择目标状态");
        }
    }

    @Override
    public void consentData(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String studentId = loginUser != null ? loginUser.getUsername() : "未知";
        log.info("审批通过，流程ID:{}，学生学号:{}", vo.getTaskId(), studentId);
    }

    @Override
    public void backToModifyData(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String studentId = loginUser != null ? loginUser.getUsername() : "未知";
        log.info("流程退回修改，学生学号:{}，退回原因:{}", studentId, vo.getRemark());
    }

    @Override
    public void cancellationData(UDLFApplyVo vo) {
        if (!isTargetForm(vo)) {
            return;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String studentId = loginUser != null ? loginUser.getUsername() : "未知";
        log.info("流程已取消，学生学号:{}", studentId);
    }
}